﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Tss.MagicWeb.Infrastructure
{
    public static class CustomHtmlHelpers
    {
        public static MvcHtmlString TextInput(this HtmlHelper html, String label, String id)
        {
            return html.TextInput(label, id, (Dictionary<String, String>)null);
        }

        public static MvcHtmlString TextInput(this HtmlHelper html, String label, String id, Dictionary<String, String> errors)
        {
            return html.TextInput(label, id, InputTypes.Text, errors);
        }

        public static MvcHtmlString TextInput(this HtmlHelper html, String label, String id, InputTypes inputType)
        {
            return html.TextInput(label, id, inputType, null);
        }

        public static MvcHtmlString TextInput(this HtmlHelper html, String label, String id, InputTypes inputType, Dictionary<String, String> errors)
        {
            bool isValidationError = errors != null && errors.ContainsKey(id);

            TagBuilder outerContainer = new TagBuilder("div");
            outerContainer.AddCssClass("control-group");

            if (isValidationError)
            {
                outerContainer.AddCssClass("error");
            }

            TagBuilder labelContainer = new TagBuilder("label");
            labelContainer.AddCssClass("control-label");
            labelContainer.MergeAttribute("for", id);
            labelContainer.SetInnerText(label);

            outerContainer.InnerHtml += labelContainer.ToString();

            TagBuilder innerContainer = new TagBuilder("div");
            innerContainer.AddCssClass("controls");

            TagBuilder input = new TagBuilder("input");
            input.MergeAttribute("type", inputType.ToString());
            input.AddCssClass("input-xlarge");
            input.MergeAttribute("name", id);
            input.MergeAttribute("id", id);
            innerContainer.InnerHtml += input.ToString();

            if (isValidationError)
            {
                TagBuilder span = new TagBuilder("span");
                span.AddCssClass("help-inline");
                span.SetInnerText(errors[id]);
                innerContainer.InnerHtml += span.ToString();
            }

            outerContainer.InnerHtml += innerContainer.ToString();

            return new MvcHtmlString(outerContainer.ToString());
        }
    }
}